<template>
  <el-dialog title="分配角色" :visible.sync="dialogFormVisible">
    <el-form>
      <el-form-item>
        <el-select v-model="rolesSelected" multiple placeholder="请选择">
          <el-option
            v-for="item in allRoles"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { allocateUserRoles, getAllRoles, getUserRoles } from '@/services/role'

  export default {
    name: 'AllocRole',
    props: {
      dialogFormVisible: {
        type: Boolean,
        required: true,
      },
      userId: {
        type: Number,
      }
    },
    data() {
      return {
        allRoles: [],
        rolesSelected: [],
      }
    },
    created() {
      this.loadRoles()
    },
    methods: {
      async loadRoles() {
        const { code, data } = await getAllRoles()
        if (code === '000000') {
          this.allRoles = data
        }
      },
      async onSubmit() {
        const { code } = await allocateUserRoles({
          userId: this.userId,
          roleIdList: this.rolesSelected,
        })
        if (code === '000000') {
          this.$message.success('操作成功')
        }
        this.rolesSelected = []
        this.$emit('close')
      },
    },
    watch: {
      userId(value) {
        console.log('userId>>', value)
        if (value) {
          getUserRoles(value).then(({ code, data }) => {
            if (code === '000000') {
              this.rolesSelected = data.map(item => item.id)
            }
          })
        }
      }
    }
  }
</script>
